<template>
    <div class="app-container video-mix">
        <el-row :gutter="24">
            <el-col :span="10">
                <el-card>
                    <template #header>
                        <div class="left-card-header">
                            <el-form inline>
                                <el-form-item :label="$t('Channel')">
                                    <el-select v-model="Channel" :placeholder="$t('select_placeholder')"
                                        style="width:150px;" @change="setChannel">
                                        <el-option v-for="item in channelOptions" :key="item.value" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item :label="$t('Layout')">
                                    <el-select v-model="Layout" :placeholder="$t('select_placeholder')" style="width:150px;"
                                        @change="SysLayoutChange">
                                        <el-option v-for="item in layoutOptions" :key="item.value" :label="$t(item.label)"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                            <!-- <el-icon>
                                <Tools />
                            </el-icon> -->
                        </div>

                    </template>
                    <img :src="imgSrc" alt="" @error="handleError" style="display: block;width: 100%;height: 450px;">
                </el-card>
            </el-col>
            <el-col :span="14">
                <el-card>
                    <template #header>
                        <div style="height: 32px;line-height:32px;margin-bottom:7px">{{ $t('Layout config') }}</div>
                    </template>
                    <div style="position: relative;height: 450px;">
                        <div class="templeLay" v-for="item in layoutDomList"
                            :style="{ position: 'absolute', padding: '10px', left: item.left, top: item.top, width: item.width, height: item.height, border: '1px solid #ddd', 'z-index': item.zIndex, 'background-color': item.bgColor }">
                            <el-select v-model="item.value" :placeholder="$t('select_placeholder')" style="width:150px;"
                                @change="update">
                                <el-option v-for="opt in item.option" :key="opt.value" :label="$t(opt.label)"
                                    :value="opt.value"
                                    :disabled="selectedDomValue.includes(opt.value) && opt.value != item.value"></el-option>
                            </el-select>
                            <el-button @click="() => { setMute(item) }">
                                <svg-icon icon-class="vol" :color="item.isMute ? '#ddd' : theme" />
                            </el-button>
                        </div>
                    </div>

                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup name="video-mix">
import modal from "@/plugins/modal.js"
import RPC from "@/api/rpc"
import getJson from "@/api/getJson"
import i18n from '@/lang'
import { cloneDeep } from 'lodash'
import { nextTick } from 'vue'
import errorImg from "@/assets/images/error-img.png"
import useSettingsStore from '@/store/modules/settings'

const settingsStore = useSettingsStore()
// 主题颜色
const theme = computed(() => settingsStore.theme);

let hardware = reactive({})
let config = reactive([])
let Channel = ref()
let Layout = ref('')
let configOptions = ref([])
let channelOptions = ref([])
let mixV = ref([])
let curChn = ref(-1)
let curLayIndex = ref(-1)
let mixCfg = reactive({})
let imgSrc = ref('')
let layoutDomList = reactive([])
let getDefLaysTimer = null
handleInit()
function handleInit() {
    config.length = 0
    configOptions.value = []
    let p1 = getJson('/config/hardware.json')
    let p2 = getJson('/config/config.json')

    Promise.all([p1, p2]).then(res => {

        let [r1, r2] = res

        hardware = Object.assign(hardware, r1.data)

        config.push(...r2.data)

        config.forEach(conf => {

            configOptions.value.push({ value: conf.id, label: conf.name })

            if (conf.type == "mix") {
                channelOptions.value.push({ value: conf.id, label: conf.name })
                mixV.value = conf.srcV
            }
        })

        getDefLays()
        clearInterval(getDefLaysTimer)
        getDefLaysTimer = setInterval(getDefLays, 1000)
    })
}


let defLays = reactive([])
let SysLayout = reactive([])
let layoutOptions = ref([])
let hasLayoutOptions = false
function getDefLays() {
    getJson("config/defLays.json?rnd=" + Math.random()).then(res => {
        defLays.length = 0
        defLays = defLays.concat(res.data)
        if (defLays.length) {
            SysLayout.length = 0
            defLays.forEach(item => {
                let las = item.layouts;
                let layout = las.length ? las.map(l => l.pos) : []
                SysLayout.push(layout)
                if (!hasLayoutOptions) {
                    layoutOptions.value.push({ value: item.layId, label: item.layNameEn })
                }

            })
            hasLayoutOptions = true
        }

        setChannel(channelOptions.value[0].value)

    })
}

function setChannel(id) {
    Channel.value = id
    curChn.value = id;
    mixCfg = config[id];
    // key值重新排序，为对比做准备
    var layList = [];
    for (var i = 0; i < mixCfg["layout"]?.length; i++) {
        var layout = mixCfg["layout"][i];
        var layObj = {
            "a": layout["a"],
            "x": layout["x"],
            "y": layout["y"],
            "w": layout["w"],
            "h": layout["h"],
            "index": layout["index"]
        }
        layList.push(layObj);
    }
    var str = JSON.stringify(layList);


    curLayIndex.value = 6;
    for (var i = 0; i < SysLayout.length; i++) {
        if (JSON.stringify(SysLayout[i]) == str) {
            Layout.value = i
            curLayIndex.value = i;
        }
    }
    if (curLayIndex.value == 6) {
        Layout.value = 6
        SysLayout[6] = mixCfg["layout"];
    }

    setLayout();
}

function SysLayoutChange(val) {
    curLayIndex.value = val
    var defLay = defLays[curLayIndex.value];
    var temp = [];
    var type = false;
    for (var i = 0; i < defLay.layouts.length; i++) {
        var lay = defLay.layouts[i];
        if (lay.id < 0) {
            temp.push("-1");
        } else {
            type = true;
            temp.push(lay.id + "");
        }
    }
    var mixSrcV = mixCfg["srcV"];

    //如果自定义布局中存在指定输入源
    if (type) {
        mixCfg["srcV"] = temp;
        // for(var i=0;i<mixSrcV.length;i++){
        //     if( i >= temp.length)
        //         break;
        //     if(mixSrcV[i] == "-1")
        //         continue;
        //     var mark = false;
        //     for(var j=0;j<temp.length;j++){
        //         if(temp[j] == mixSrcV[i])
        //             mark = true;
        //     }
        //     if(!mark)
        //         temp[i] = mixSrcV[i];
        // }
        // mixCfg["srcV"] = temp;
    }
    setLayout();
    update()
}
let selectedDomValue = ref([])
function setLayout() {
    var layout = SysLayout[curLayIndex.value];
    var srcA = mixCfg["srcA"];
    var srcV = mixCfg["srcV"];
    let newOptions = [
        { value: -1, label: '空' },
        ...cloneDeep(configOptions.value)
    ]
    layoutDomList.length = 0
    selectedDomValue.value = []
    layout.forEach((item, i) => {
        let optlist = cloneDeep(newOptions)
        var color = 128;
        if (i % 2 == 0) {
            color += 25 * (i / 2);
        } else {
            color -= 25 * (i / 2 + 1);
        }
        if (srcV[i] == 'NaN') {
            srcV[i] = '-1'
        }
        layoutDomList.push({
            option: optlist,
            left: item.x * 100 + '%',
            top: item.y * 100 + '%',
            width: item.w * 100 + '%',
            height: item.h * 100 + '%',
            zIndex: i,
            bgColor: `rgb(${color},${color},${color})`,
            value: srcV[i] ? Number(srcV[i]) : -1,
            isMute: (!srcA.includes(srcV[i])) || srcV[i] == -1
        })
    })
    getSelectedDomValue()
}
function setMute(item) {
    if (item.value == -1) { return }
    item.isMute = !item.isMute
    update()
}
function getSelectedDomValue() {
    selectedDomValue.value = layoutDomList.map(item => item.value).filter(val => val != -1)
}
function update() {
    getSelectedDomValue()
    var srcV = new Array();
    var srcA = new Array();
    layoutDomList.forEach(item => {
        srcV.push(item.value + '')
        if (!item.isMute) { srcA.push(item.value + '') }
    })
    mixCfg["srcA"] = srcA;
    mixCfg["srcV"] = srcV;
    mixCfg["layout"] = toRaw(SysLayout[curLayIndex.value]);
    save()
}

var timer1 = setInterval(show, 300);
function show() {
    setTimeout(() => { RPC("enc.snap") }, 100);
    imgSrc.value = `${import.meta.env.VITE_APP_HOST}/snap/snap${curChn.value}.jpg?rnd=${Math.random()}`
}

function save() {
    clearInterval(getDefLaysTimer)

    RPC("enc.update", [JSON.stringify(config, null, 2)]).then(res => {
        modal.msgSuccess(i18n.global.t('Save success'))
        nextTick(() => {
            handleInit();
        })
    }).catch(() => {
        modal.msgError(i18n.global.t('Save failed'))
    })
}


function handleError(event) {
    var img = event.srcElement;
    if (errorImg) {
        img.src = errorImg;
    }
}

onBeforeUnmount(() => {
    clearInterval(timer1)
    clearInterval(getDefLaysTimer)
})
</script>

<style lang='scss' scoped>
.video-mix {

    .left-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 7px;

        .el-form-item--default {
            margin-bottom: 0;
        }

        .el-icon {
            cursor: pointer;
        }
    }

    .btns {
        text-align: center;
        margin-top: 20px;
    }
}
</style>